// packageI/newMedia/newMediaAdVideo/newMediaAdVideo.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    amount_id: "",
    isLoadMore: true,
    page: 1,
    total_page: 0,
    popularVideo: [],
    heightauto: "auto",
    widthauto: "auto",
    showVideo: {},
    myvideo: "",
    show: false,
    screeheight: 0,
    minStyle: true,
    firstcontent: false,
    cleartime: null,
    realIndex: 0,
    kFootshow: true,
    is_plugins: 0,

    timer: null,


    advertisingt_type: 0,
    commentsShow:false,
    readReawrdList:{},
    rewardShow:false,

    attentionRewaedData:{},
    attentionRewaedShow:false,

    reward_button:{}

    //--------
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.myvideo = wx.createVideoContext("myvideo");
    this.getinformation();

    if (options.advertisingt_type) {
      this.data.advertisingt_type = options.advertisingt_type;
    }
    if (options.vid) {
      this.setData({
        amount_id: options.vid,
      });
    }
    if (options.mid) {
      app._setMid(options.mid);
      this.sendForwardReward();
    }

    if (options.page) {
      this.setData({
        page: Number(options.page) ? Number(options.page) : 0,
      });
    }
    // 判断是否有page和vid   没有vid就是会员中心进入的样式二   有page的肯定是从列表进入
    if (options.page || !options.vid) {
      this.getData();
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  handAttentionRewaed(evt){
    this.setData({
      attentionRewaedData:evt.detail,
      attentionRewaedShow:true
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    let json = {};
    let shareImg = "";
    if (this.data.popularVideo[this.data.realIndex] && this.data.popularVideo[this.data.realIndex].cover_picture) {
      shareImg = this.data.popularVideo[this.data.realIndex].cover_picture;
    }

    json = {
      title: this.data.showVideo.title ? this.data.showVideo.title : "",
      query: "vid=" + this.data.amount_id + "&page=" + this.page + "&mid=" + mid +"&advertisingt_type="+this.data.advertisingt_type,
    };

    if (shareImg) {
      json.imageUrl = shareImg;
    }
    console.log(json);
    return json;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {

    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    let json = {};
    let shareImg = "";
    if (this.data.popularVideo[this.data.realIndex] && this.data.popularVideo[this.data.realIndex].cover_picture) {
      shareImg = this.data.popularVideo[this.data.realIndex].cover_picture;
    }
    json = {
      title: this.data.showVideo.title ? this.data.showVideo.title : "",
      path: "/packageI/newMedia/newMediaAdVideo/newMediaAdVideo?vid=" + this.data.amount_id + "&page=" + this.data.page + "&mid=" + mid+"&advertisingt_type="+this.data.advertisingt_type,
    };

    if (shareImg) {
      json.imageUrl = shareImg;
    }
    console.log(json);
    return json;
  },

  getData() {
    let that = this;
    let urlStr;

    urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.get-list");
    urlStr += "&page=" + this.data.page;

    urlStr += "&advertisingt_type=" + this.data.advertisingt_type;
    if (this.data.advertisingt_type == 1) {
      urlStr += "&genre=" + 4;
    }

    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.data.isLoadMore = true;

          that.data.total_page = res.data.list.last_page;
          if (!that.data.total_page) {
            that.data.total_page = 0;
          }
          that.setData({
            popularVideo: res.data.list.data,
            reward_button:res.data.reward_button
          });
          let popularVideoData = res.data.list.data;

          if (that.data.amount_id) {
            for (let i = 0; i < res.data.list.data.length; i++) {
              if (res.data.list.data[i].id == that.data.amount_id) {
                that.setData({
                  showVideo: res.data.list.data[i],
                });
                popularVideoData.splice(0, i);
                that.setData({
                  popularVideo: popularVideoData,
                });
                wx.setNavigationBarTitle({
                  title: that.data.showVideo.title,
                });
                that.setData({
                  firstcontent: true,
                });
                that.clickSwiperbtn(0);
                return;
              }
            }
            wx.setNavigationBarTitle({
              title: that.data.showVideo.title,
            });
          } else {
            that.setData({
              showVideo: that.data.popularVideo[0],
            });
            that.clickSwiperbtn(0);
          }

          that.setData({
            firstcontent: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getinformation() {
    try {
      const res = wx.getSystemInfoSync();
      let windowHeight = res.windowHeight;
      let windowWidth = res.windowWidth;
      this.setData({
        heightauto: windowHeight + "px",
        widthauto: windowWidth + "px",
      });
      this.data.screeheight = windowHeight;
    } catch (e) {
      // Do something when catch error
    }
  },
  clickSwiperbtn(e) {
    let index = 0;
    if (e.currentTarget) {
      index = e.currentTarget.dataset.index;
    } else {
      index = e;
    }
    this.clickSwiper(index);
  },
  clickSwiper(e) {
    let index = e;
    console.log("zhixing");
    if (this.data.popularVideo[index].show && this.data.amount_id === this.data.popularVideo[index].id) {
      this.setData({
        show: false,
        ["popularVideo[" + index + "].show"]: false,
      });
      this.data.myvideo.pause();
      return;
    }
    this.judgmentpic(index);
    this.setData({
      show: true,
      amount_id: this.data.popularVideo[index].id,
      ["popularVideo[" + index + "].show"]: true,
    });
    this.data.logID = 0;
    this.data.myvideo.play();
    this.selectComponent("#commentList").getStickComment();
    this.addReadReward();
    console.log("执行-----------");
    //this.getStickComment();
    //this.data.getCommentFlag=true;
  },
  popularVideoChange(e) {
    clearTimeout(this.data.cleartime);
    let realIndex = e.detail.current;
    let that = this;
    that.data.realIndex = realIndex;
    that.data.AnswerID = 0;
    that.data.cumulativeDuration = parseInt(that.data.cumulativeDuration + that.data.currentDuration); //切换视频时计算累计
    that.data.currentDuration = 0;
    that.judgmentpic_2(realIndex);
  },
  judgmentpic_2(index) {
    let realIndex = index;
    let that = this;
    try {
      if (that.data.popularVideo[realIndex] && that.data.popularVideo[realIndex].cover) {
        const query = wx.createSelectorQuery();
        query.select("#pic_" + realIndex).boundingClientRect();
        query.exec(function (res) {
          let screeheight = that.data.screeheight;
          if (res[0] && res[0].height) {
            let imgheight = res[0].height;
            if (imgheight > Math.ceil(screeheight * (7 / 8))) {
              that.setData({
                minStyle: false,
              });
              that.getvideomessage(realIndex);
            } else {
              that.setData({
                minStyle: true,
              });
              that.getvideomessage(realIndex);
            }
          } else {
            that.setData({
              minStyle: true,
            });
            that.getvideomessage(realIndex);
          }
        });
      } else {
        that.setData({
          minStyle: true,
        });
        that.getvideomessage(realIndex);
      }
    } catch (e) {
      that.setData({
        minStyle: true,
      });
      that.getvideomessage(realIndex);
      //TODO handle the exception
    }
  },
  getvideomessage(realIndex) {
    let that = this;
    if (realIndex == that.data.popularVideo.length - 2) {
      that.getMoreData();
    }
    this.data.myvideo.pause();
    that.setData({
      show: false,
      showVideo: that.data.popularVideo[realIndex],
    });
    if (realIndex === 0) {
      this.setData({
        ["popularVideo[" + realIndex + "].show"]: false,
        ["popularVideo[" + (realIndex + 1) + "].show"]: false,
      });
    } else {
      this.setData({
        ["popularVideo[" + (realIndex - 1) + "].show"]: false,
        ["popularVideo[" + realIndex + "].show"]: false,
      });
      if (that.data.popularVideo[realIndex + 1]) {
        this.setData({
          ["popularVideo[" + (realIndex + 1) + "].show"]: false,
        });
      }
    }
    wx.setNavigationBarTitle({
      title: that.data.showVideo.title,
    });
    wx.setStorageSync("circle_invitation_id", this.data.showVideo.id);
    this.data.cleartime = setTimeout(() => {
      that.clickSwiper(realIndex);
    }, 300);
    //切换结束时
  },
  getMoreData() {
    const that = this;
    that.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.get-list");
      app._getNetWork({
        url: urlStr,
        data: {
          page: this.data.page,
        },
        success: function (resdata) {
          that.data.isLoadMore = true;
          var res = resdata.data;
          if (res.result == 1) {
            let myData = res.data.list.data;
            that.setData({
              popularVideo: that.data.popularVideo.concat(myData),
            });
          } else {
            that.data.page = that.data.page - 1;
            that.data.isLoadMore = false;
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },



  judgmentpic(index) {
    let realIndex = index;
    let that = this;
    const query = wx.createSelectorQuery();
    query.select("#pic_" + realIndex).boundingClientRect();
    query.exec(function (res) {
      let screeheight = that.data.screeheight;
      let imgheight = res[0].height;
      if (imgheight > Math.ceil(screeheight * (7 / 8))) {
        that.setData({
          minStyle: false,
        });
      } else {
        that.setData({
          minStyle: true,
        });
      }
    });
  },
  endedPlay() {
    console.log("播放结束");
    // this.data.cumulativeDuration = parseInt(this.data.cumulativeDuration + this.data.currentDuration);//结束视频时计算累计
    // this.data.currentDuration = 0;
    //this.getSubject();
  },
  onPlaying() {
    console.log("onPlaying=================");
    // if(this.data.maxTime != 0&&this.data.is_openRedpack){
    // 	this.getViewTimelog();
    // }
  },

  setCommentShow(){
    this.setData({commentsShow:!this.data.commentsShow});
  },
  setRewardShow(){
    this.setData({
      rewardShow:!this.data.rewardShow
    });
  },


  //添加阅读奖励
  addReadReward(){
    let {amount_id,readReawrdList} = this.data;
    if(readReawrdList[amount_id]) return;
    this.data.readReawrdList[amount_id]=amount_id;
    let urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.advertisingt-info");
    app._getNetWork({
      url: urlStr,
      data: {
        advertisingt_id:amount_id
      },
      success: (resdata) => {
        let res = resdata.data;
        if(res.result!=1) return;
        let details = res.data;
        this.setData({reward_name:details.reward_name});
        if(details.behavioral && details.behavioral.is_reward && details.behavioral.is_reward==1){
          this.setData({
            attentionRewaedData:details.behavioral,
            attentionRewaedShow:true
          });
        }
      }
    });
  },

  //转发分享进来的奖励
  sendForwardReward(){
    let urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.forward-reward");
    app._getNetWork({
      url: urlStr,
      data: {
        advertisingt_id: this.data.amount_id
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
      }
    });
  },

  handCommentSuccess(evt){
    let type = evt.detail.type;
    let comment_count = this.data.popularVideo[this.data.realIndex].comment_count;
    if(type == "add"){
      comment_count++;
    }else if(type=="reduce"){
      comment_count--;
    }
    let name="popularVideo["+this.data.realIndex+"].comment_count";
    this.setData({
      [name]:comment_count,
      'showVideo.comment_count':comment_count
    });
  },

  setAttentionRewaedShow(){
    this.setData({
      attentionRewaedShow:!this.data.attentionRewaedShow
    });
  },
  //关注接口
  sendAttention(evt) {
    let details = evt.currentTarget.dataset.item;
    let index = evt.currentTarget.dataset.index;
    let is_attention = details.is_attention;
    let urlStr="";
    let json={};
    if(is_attention){
      urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.cancel-attention");
      json.advertisingt_member = details.member_id;
    }else {
      urlStr = app.getNetAddresss("plugin.new-media-advertising.frontend.media-advertisingt.attention");
      json.advertisingt_id =  details.id;
    }

    app._getNetWork({
      url: urlStr,
      data:json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);

        let changeData={};
        changeData['popularVideo['+index+'].is_attention'] = is_attention ? false : true;
        if(res.data.is_reward==1){
          changeData['attentionRewaedData'] = res.data;
          changeData['attentionRewaedShow'] = true;
        }

        this.setData(changeData);
      }
    });
  },

  handFavorites(evt){
    let index = evt.target.dataset.index;
    let favorites_count = evt.detail.favorites_count;
    let is_favorites = evt.detail.is_favorites;
    let changeData={};
    changeData['popularVideo['+index+'].is_favorites'] = is_favorites ? false : true;
    changeData['popularVideo['+index+'].favorites_count'] = favorites_count;
    this.setData(changeData);
  },
  handLike(evt){
    let index = evt.target.dataset.index;
    let like_count = evt.detail.like_count;
    let is_like = evt.detail.is_like;
    let changeData={};
    changeData['popularVideo['+index+'].is_like'] = is_like ? false : true;
    changeData['popularVideo['+index+'].like_count'] = like_count;
    this.setData(changeData);
  },




  
 
});